package com.imyuanma.qingyun.common.config.security;

import com.imyuanma.qingyun.common.model.ECommonResultCode;
import com.imyuanma.qingyun.common.model.response.Result;
import com.imyuanma.qingyun.common.util.WebUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 访问拒绝处理
 *
 * @author wangjy
 * @date 2022/07/18 23:16:37
 */
@Component
public class DefaultAccessDeniedHandler implements AccessDeniedHandler {
    private static final Logger logger = LoggerFactory.getLogger(DefaultAccessDeniedHandler.class);
    /**
     * Handles an access denied failure.
     *
     * @param request               that resulted in an <code>AccessDeniedException</code>
     * @param response              so that the user agent can be advised of the failure
     * @param accessDeniedException that caused the invocation
     * @throws IOException      in the event of an IOException
     * @throws ServletException in the event of a ServletException
     */
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        logger.info("[访问拒绝处理] 访问拒绝处理,URI={}", request.getRequestURI());
        if (WebUtil.isAjaxRequest(request)) {
            WebUtil.write2Response(response, Result.error(ECommonResultCode.NOT_AUTH));
        } else {
            //请求的url
            response.sendRedirect("/page/login.html");
        }
    }
}
